import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
const service = axios.create({
  // 设置基地址和超时时间
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 设置请求拦截器
service.interceptors.request.use(config => {
  if (store.state.user.token) {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})
// 设置响应拦截器
service.interceptors.response.use(response => {
  if (!response.data.success) return Promise.reject(new Error('请求错误'))
  Message.success(response.data.message)
  return response.data
}, error => {
  console.log(error.response)
  if (error.response.status === 401 || error.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  return Promise.reject(error)
})
export default service
